package com.codingvip.link;

import com.sun.istack.internal.localization.NullLocalizable;

public class MergeList {
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(4);
        l1.next = l2;
        l2.next = l3;

        ListNode l4 = new ListNode(1);
        ListNode l5 = new ListNode(3);
        ListNode l6 = new ListNode(4);
        l4.next = l5;
        l5.next = l6;
        MergeList mergeList = new MergeList();
        ListNode node = mergeList.mergeTwoLists(l1, null);
        System.out.println(node);

    }

        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1 == null ) {
                return l2;
            }
            if (l2 == null) {
                return l1;
            }
            ListNode merged = null;
            ListNode tail = null;
            while (l1 != null && l2 !=null) {
                if (l1.val < l2.val) {
                    ListNode newNode=new ListNode(l1.val);
                    if (merged == null) {
                        merged = newNode;
                        tail = merged;
                    }
                    tail.next = newNode;
                    tail = tail.next;
                    l1 = l1.next;
                }else{
                    ListNode newNode=new ListNode(l2.val);
                    if (merged == null) {
                        merged = newNode;
                        tail = merged;
                    }
                    tail.next = newNode;
                    tail = tail.next;
                    l2 = l2.next;
                }


            }
            while (l1!= null) {

                ListNode newNode=new ListNode(l1.val);
                if (merged == null) {
                    merged = newNode;
                    tail = merged;
                }
                tail.next = newNode;
                tail = tail.next;

                l1 = l1.next;
            }
            while (l2!= null) {
                ListNode newNode=new ListNode(l2.val);
                if (merged == null) {
                    merged = newNode;
                    tail = merged;
                }
                tail.next = newNode;
                tail = tail.next;
                l2 = l2.next;
            }
            return merged;
        }

        private void addNode(ListNode merged, ListNode tail, int val) {
            ListNode newNode=new ListNode(val);
            if (merged == null) {
                merged = newNode;
                tail = merged;
                return;
            }
            tail.next = newNode;
            tail = tail.next;

        }

}
